package com.topscomm.mis.cbb.file.compare.cj.pojo.dto;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class CompareDto implements Serializable {

    protected String getApiModelName(Class<?> clazz) {
        ApiModelProperty annotation = clazz.getAnnotation(ApiModelProperty.class);
        return (annotation != null) ? annotation.value() : "";
    }

    /**
     * description 获取属性及属性名称
     * @author wxm
     * @date 2023-06-13 10:18:53
     * @param clazz 类
     * @return com.alibaba.fastjson.JSONArray
     * @modify
     */
    public static JSONArray getApiModelProperty (Class clazz) {
        JSONArray propertyArray = new JSONArray();

        // 2.获取类的属性
        Field[] declaredFields = clazz.getDeclaredFields();
        // 3.遍历属性，获取属性上ApiModelProperty的值，属性的名，存入Properties
        if (declaredFields.length != 0) {
            for (Field field : declaredFields) {
                if (field.getAnnotation(ApiModelProperty.class) != null) {
                    // key和value可根据需求存
                    // 这存的key为注解的值，value为类属性名
                    JSONObject propertyObject = new JSONObject();
                    propertyObject.put("code",field.getName());
                    propertyObject.put("name",field.getAnnotation(ApiModelProperty.class).value());
                    // 不是Boolean类型的继续找子类
                    if (field.getType() != Boolean.class && field.getType() != boolean.class){
                        Class<?> subClazz;
                        Method method;
                        Object result = null;
                        try {
                            subClazz = Class.forName(field.getType().getName());
                            method = subClazz.getMethod("getApiModelProperty", Class.class);
                            field.setAccessible(true);
                            result = method.invoke(null, subClazz);
                        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                        JSONArray children = JSONArray.parseArray(JSONObject.toJSONString(result));
                        propertyObject.put("children",children);
                    }
                    propertyArray.add(propertyObject);
                }
            }
            return propertyArray;
        }
        return null;
    }
}